from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.decorators import action, authentication_classes, permission_classes
from rest_framework.pagination import PageNumberPagination
from django.shortcuts import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from browse.models import Post, Tag, Category, Configration
from browse.serializers import PostListSerializer, PostSerializer, TagSerializer, CategorySerializer, \
    ConfigrationSerializer


class PostPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'pageSize'
    page_query_param = 'pageNum'
    max_page_size = 30


class PostViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Post.objects.filter(status__in=[1, 2, 3])
    pagination_class = PostPagination

    def get_queryset(self):
        tag_id = self.request.query_params.get('tagId')
        category_id = self.request.query_params.get('categoryId')
        if tag_id is not None:
            tag = get_object_or_404(Tag, id=tag_id)
            queryset = tag.post_set.filter(status__in=[1, 2, 3])
        elif category_id is not None:
            category = get_object_or_404(Category, id=category_id)
            queryset = category.post_set.filter(status__in=[1, 2, 3])
        else:
            queryset = Post.objects.filter(status__in=[1, 2, 3])
        return queryset

    # 这样保证list查询时不出现content字段，减轻查询压力
    def get_serializer_class(self):
        if self.action == 'list':
            return PostListSerializer
        elif self.action == 'retrieve':
            return PostSerializer


class TagViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer


class CategoryViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer


class ConfigurationViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Configration.objects.all()
    serializer_class = ConfigrationSerializer

    # authentication_classes = (TokenAuthentication,)
    # permission_classes = (IsAuthenticated,)

    @action(detail=False, methods=['get'])
    def get_blog_info(self, request):
        # 获取博主信息
        bloggers = Configration.objects.filter(category='blogger').values()
        bloggers_json = list(bloggers)
        # 获取社交媒体配置信息
        societies = Configration.objects.filter(category='society').values()
        societies_json = list(societies)
        # 获取发布博文数
        post_num = Post.objects.filter(status=1).count()
        # 获取博文分类数
        post_category_num = Category.objects.count()
        # 获取标签数
        post_tag_num = Tag.objects.count()
        # 组装返回前台的信息
        data = {'bloggers': bloggers_json, 'societies': societies_json, 'postNum': post_num,
                'postCategoryNum': post_category_num, 'postTagNum': post_tag_num}

        return Response(data)
